package com.gamesite.gamesite.core.controller;


import com.gamesite.gamesite.core.pojo.User;
import com.gamesite.gamesite.core.service.UserService;
import com.gamesite.gamesite.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;


    // 查询所有用户
    @GetMapping("/getAll")
    public List<User> getAllUsers() {
        return userService.list(); // 查询所有用户
    }


    // 根据 ID 查询用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id); // 根据 ID 查询用户
    }


    // 添加用户
    @PostMapping("/addUser")
    public String addUser(@RequestBody User user) {
        userService.save(user); // 添加用户
        return "User added successfully!";
    }


    // 更新用
    @PutMapping("/update/{id}")
    public String updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateById(user); // 更新用户
        return "User updated successfully!";
    }


    // 删除用户
    @DeleteMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.removeById(id); // 删除用户
        return "User deleted successfully!";
    }

    // 注册用户
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (userService.getByUsername(user.getUsername()) != null) {
            return Result.fail("用户名已存在");
        }
        userService.register(user); // 注册用户

        return Result.success("注册成功");
    }

    @GetMapping("/getUserByUsername")
    public Result getUserByUsername(@RequestParam String username) {
        return Result.success(userService.getByUsername(username));
    }
}